import axios from 'axios'
import Vue from 'vue'
import { Message, Loading } from 'element-ui'
import Storage from 'vue-ls'

// options = {
//   namespace: 'vuejs__', // key键前缀
//   name: 'ls', // 命名Vue变量.[ls]或this.[$ls],
//   storage: 'local', // 存储名称: session, local, memory
// }
Vue.use(Storage);

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 30000 // request timeout
})
 
// request interceptor
// 添加请求拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  config.headers['Cache-Control'] = 'no-cache' // ie清缓存，否则无法正常刷新
  config.headers['Pragma'] = 'no-cache' // HTTP/1.1版本，ie清缓存，否则无法正常刷新
  
  // const token = Vue.ls.get("ACCESS_TOKEN") //token是放在vuex中的state中
  // if (token) {
  //   config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  // }

  config.headers['X-Access-Token'] = '51ff22097c20a90c05d0981c3ac77b7d';
  if (config.formType && config.formType === 1) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
 
    config.transformRequest = [function (data) {
      // Do whatever you want to transform the data
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret.substring(0, ret.length - 1)
    }]
  }
  if (config.showLoading) {
    showFullScreenLoading()
  }

  if (config.method == 'get') {
    config.params = {
      _t: Date.parse(new Date()) / 1000, //让每个请求都携带一个不同的时间参数，防止浏览器缓存不发送请求
      ...config.params
    }
  }

  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

/**
 * 响应拦截器中的error错误处理
 */
const err = (error) => {
  if (error.response) {
    switch (error.response.status) {
      case 401:
        console.log({
          message: '系统提示',
          description: '未授权，请重新登录',
          duration: 4
        })
        break
      case 403:
        console.log({
          message: '系统提示',
          description: '拒绝访问'
        })
        break

      case 404:
        console.log({
          message: '系统提示',
          description: '很抱歉，资源未找到!',
          duration: 4
        })
        break
      case 500:
        console.log({
          message: '系统提示',
          description: 'Token失效，请重新登录!'
        })
        break
      case 504:
        console.log({
          message: '系统提示',
          description: '网络超时'
        })
        break
      default:
        console.log({
          message: '系统提示',
          description: error.response.data.msg,
        })
        break
    }
  }
  return Promise.reject(error)
};

// respone interceptor
// 添加响应拦截器
service.interceptors.response.use(
  response => {
    // const token = response.headers["authorization"]
    // if (token) {
    //   Vue.ls.set("ACCESS_TOKEN", token) //token是放在vuex中的state中
    // }

    if (response.config.showLoading) {
      tryHideFullScreenLoading()
    }
    var res = response.data
    // 以下请根据后端返回具体格式修改!!!!!
    if (res.code === 200) {
      return res
    } else {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000,
        offset:100
      })
      return Promise.reject(res)
    }
  },
  error => {
    // 错误处理
    tryHideFullScreenLoading()
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
 
// 加载封装
let loading
function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
// 关闭加载
function endLoading () {
  loading.close()
}
let needLoadingRequestCount = 0
export function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}
 
export function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
export default service